/**
 * BaseFileHandler class for use by subsequence FileHandler classes
 * @author Tobias
 */

package ModelLayer.FileHandlers;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;

public abstract class BaseFileHandler {
	
	private String fileName;
	
	public BaseFileHandler(String fileName)
	{
		this.fileName = fileName;
	}
	
    /**
     * Method used to allow other FileHandlers to write to the file.
     */
	protected void saveToFile(Object obj)
	{
		File destination;
		try {
			destination = makeAbsoluteFileName(fileName);
			ObjectOutputStream os = new ObjectOutputStream(new FileOutputStream(destination));
			os.writeObject(obj);
			os.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
    /**
     * Method used to allow other FileHandlers to read the file.
     */
	protected Object readFromFile()
	{
		Object objectToReturn = null;
		
		if(!fileExists()){
			return null;
		}
		
		URL resource = getClass().getResource(fileName);
		
        // List of exceptions.
		try{
			File source = new File(resource.toURI());
			ObjectInputStream is = new ObjectInputStream(new FileInputStream(source));
			objectToReturn = is.readObject();
			is.close();
		}catch(URISyntaxException e){
			e.printStackTrace();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}
		
		return objectToReturn;
	}
	
    /**
     * This method is used for checking whether the file exits.
     */
	protected boolean fileExists()
	{
		return getClass().getResource(fileName) != null;
	}

    /**
     * This method is used to make sure the file is in the same place on the filesystem.
     */
	private File makeAbsoluteFileName(String fileName) throws IOException {
		try{
			File file = new File(fileName);
			if(!file.isAbsolute()){
				file = new File(getProjectFolder(), fileName);
			}
			return file;
			
		}catch(URISyntaxException e){
			throw new IOException("Unable to create a valid filename for " + fileName);
		}
	}
    
    /**
     * Method used to find the project folder
     * @return File List
     */
	private File getProjectFolder() throws URISyntaxException
	{
		String classFile = getClass().getSimpleName() + ".class";
		URL url = getClass().getResource(classFile);
		URI fileUri = url.toURI();
		return new File(fileUri).getParentFile();
	}
	
	
	
}
